<template>
  <div>
    <el-dialog
      :model-value="props.dialogVisible"
      title="批量导入用户"
      width="600px"
      :close-on-click-modal="false"
      :before-close="handleClose">
      <div>
        <el-link type="primary" @click="handleDownTemp">下载模板</el-link>
      </div>
      <div class="mt16">
        <!-- <el-button type="primary" @click="uploadFile">选择文件</el-button>
        <input id="upload" type="file" style="display: none;" @change="handleChangeUpload"> -->
        <el-upload
          ref="upload"
          accept=".xlsx"
          :auto-upload="false"
          :limit="1"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :on-change="handleChangeUpload">
          <el-button type="primary">选择文件</el-button>
        </el-upload>
      </div>
      <div v-if="readyUpload" class="mt16">
        <el-button type="primary" @click="confirmUpload">上传确认</el-button>
      </div>
      <div class="mt16 result" v-show="showResult">
        <div>
          <span>上传结果</span>
          <span class="total">成功：<b style="color: #409eff;">{{successNum}}</b>， 失败: <b style="color: #f56c6c;">{{failNum}}</b></span>
        </div>
        <div v-if="failNum !== 0" class="mt16">
          <div>详情：</div>
          <el-table :data="tableData" :max-height="400" class="nr-table">
            <el-table-column label="用户名称" prop="username"></el-table-column>
            <el-table-column label="用户名称" prop="phoneNum"></el-table-column>
            <el-table-column label="备注" prop="info"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="UserGroupDialog">
import { ref, reactive, watch, ComponentInternalInstance, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { userDownloadTemplate, userBatchInsert } from '@/api/user-manage'
import * as XLSX from 'xlsx'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const emit = defineEmits(['submit', 'update:dialogVisible'])
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  }
})

const readyUpload = ref(false)
const upload = ref<any>(null)
const showResult = ref(false)
const tableData = ref<any>([])
const uploadArr = ref<any>([])
const successNum = ref(0)
const failNum = ref(0)

// 下载模板
const handleDownTemp = async () => {
  await userDownloadTemplate().then((res: any) => {
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    if ('msSaveOrOpenBlob' in navigator) {
      (window.navigator as any).msSaveOrOpenBlob(blob, `用户导入模板.xlsx`)
    } else {
      const a = document.createElement('a')
      a.href = URL.createObjectURL(blob)
      a.download = `用户导入模板.xlsx`
      a.style.display = 'none'
      document.body.append(a)
      a.click()
      URL.revokeObjectURL(a.href)
      document.body.removeChild(a)
    }
  }).catch(err => {
    console.log(err)
  })
}

// 点击上传
const uploadFile = () => {
  let upload = document.getElementById('upload')
  upload?.click()
  // showResult.value = true
}

// 上传文件改变事件
const handleChangeUpload = (file: any) => {
  if (file.raw.name.indexOf('.xlsx') === -1) {
    upload.value!.clearFiles()
    readyUpload.value = false
    ElMessage.error('上传图片格式必须为 xlsx！')
    return false
  }
  readyUpload.value = true
  readExcel(file.raw)
}

// 上传处理
const handleExceed = (files: any) => {
  readyUpload.value = true
  upload.value!.clearFiles()
  const file = files[0]
  upload.value!.handleStart(file)
}

// 删除上传
const handleRemove = () => {
  readyUpload.value = false
}

// 数据处理
const readExcel = (files: any) => {
  const fileReader = new FileReader()
  fileReader.readAsArrayBuffer(files)
  fileReader.onload = (files: any) => {
    const data = files.target.result
    const workbook = XLSX.read(data, {
      type: 'binary'
    })
    const wsname = workbook.SheetNames[0]
    const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
    // console.log(ws)
    let arr = <any>[]
    ws.map((item: any) => {
      arr.push({
        username: `${item['用户名']}`,
        phoneNum: `${item['手机号']}`
      })
    })
    uploadArr.value = [...arr]
  }
  // fileReader.readAsBinaryString(files)
}

// 关闭弹窗
const handleClose = () => {
  tableData.value = []
  readyUpload.value = false
  showResult.value = false
  upload.value!.clearFiles()
  proxy?.$emit('update:dialogVisible', false)
}

// 上传确认
const confirmUpload = async () => {
  let params = {
    userList: uploadArr.value
  }
  await userBatchInsert(params).then((res: any) => {
    if (res.code === 0) {
      ElMessage.success(`导入成功！`)
      emit('submit')
      // handleClose()
      showResult.value = true
      if (res.data) {
        failNum.value = res.data.length
        successNum.value = uploadArr.value.length - failNum.value
        let arr = <any>[]
        uploadArr.value.map((item: any) => {
          if (res.data.indexOf(item.phoneNum) !== -1) {
            arr.push(Object.assign(item, { info: '手机号已注册！' }))
          }
        })
        tableData.value = [...arr]
      } else {
        successNum.value = uploadArr.value.length
        failNum.value = 0
      }
    } else {
      ElMessage.error(`${res.msg}`)
      showResult.value = true
      successNum.value = 0
      failNum.value = uploadArr.value.length
      let arr = <any>[]
      uploadArr.value.map((item: any) => {
        arr.push(Object.assign(item, { info: '手机号已注册！' }))
      })
      tableData.value = [...arr]
    }
  }).catch(err => {
    console.log(err)
  })
}
</script>

<style lang="stylus" scoped>
@import '../../style/base.styl'

.total
  margin-left 16px
  color #aaa
</style>
